package main

import (
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// 模拟游戏服收到的请求结构
type GameMergeRequest struct {
	SourceDSNs []string               `json:"source_dsns"`
	TargetDSN  string                 `json:"target_dsn"`
	Options    map[string]interface{} `json:"options"`
	TraceID    string                 `json:"trace_id"`
}

// 模拟游戏服的响应
type GameMergeResponse struct {
	Status string                 `json:"status"` // success / failed
	Detail string                 `json:"detail"`
	Stats  map[string]interface{} `json:"stats"`
}

func main() {
	rand.Seed(time.Now().UnixNano())
	r := gin.Default()

	r.POST("/api/merge/execute", func(c *gin.Context) {
		var req GameMergeRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		log.Printf("🟢 收到合服请求 TraceID=%s", req.TraceID)

		// 输出所有 DSN
		for i, dsn := range req.SourceDSNs {
			log.Printf("   旧库[%d]: %s", i+1, dsn)
		}
		log.Printf("   新库: %s", req.TargetDSN)
		log.Printf("   参数: %+v", req.Options)

		// 模拟执行（2-4 秒）
		duration := time.Duration(2+rand.Intn(3)) * time.Second
		time.Sleep(duration)

		// 随机 成功/失败
		success := rand.Intn(100) > 10 // 90% 成功概率
		if success {
			resp := GameMergeResponse{
				Status: "success",
				Detail: fmt.Sprintf("合服成功，用时 %.1f 秒", duration.Seconds()),
				Stats: map[string]interface{}{
					"merged_rows": 123456,
					"duration_s":  duration.Seconds(),
				},
			}
			c.JSON(http.StatusOK, resp)
			log.Printf("✅ TraceID=%s 合服成功", req.TraceID)
		} else {
			resp := GameMergeResponse{
				Status: "failed",
				Detail: fmt.Sprintf("合服失败，可能存在数据冲突 TraceID=%s", req.TraceID),
			}
			c.JSON(http.StatusOK, resp)
			log.Printf("❌ TraceID=%s 合服失败", req.TraceID)
		}
	})

	log.Println("🎮 模拟游戏服已启动，监听端口 :9099")
	if err := r.Run(":9099"); err != nil {
		log.Fatalf("启动失败: %v", err)
	}
}
